package com.spence.wsdemo.controller;

import com.spence.wsdemo.config.SocketConstant;
import com.spence.wsdemo.entity.WsPrincipal;
import com.spence.wsdemo.utils.SocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * @author spence_xu
 * @date 2020/5/20 16:04
 */
@Controller
@Slf4j
public class SocketController {
    @Resource
    private SocketUtils socketUtils;

    /**
     * 发送给其他用户
     *
     * @param message        消息
     * @param headerAccessor
     * @return
     */
    @MessageMapping("/send")
    public void send(@Payload String message,
                     SimpMessageHeaderAccessor headerAccessor) {
        WsPrincipal principal = socketUtils.getPrincipal(headerAccessor);
        socketUtils.sendToUser(message, SocketConstant.TEST_USER_SUBSCRIBE, principal);
    }
}
